package org.jsola.hr.common;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.jsola.hr.core.JunZiQianProperties;
import org.jsola.hr.exception.HrException;
import org.jsola.hr.vo.junziqian.JunZiQianResult;

import java.util.Map;

/**
 * 君子签请求构建参数工具类
 *
 * @author wo
 */
@Slf4j
public class JunZiQianUtil {
    /**
     * 默认加密方式:不输入使用sha256,其它可选择项md5,sha1,sha3-256
     */
    private static String ENCRY_METHOD = "sha256";

    /**
     * 填充签名数据并发送请求，默认使用POSt
     */
    public static JunZiQianResult send(Object object, JunZiQianProperties junZiQianProperties, String url) {
        Map<String, Object> map;
        if (object instanceof Map) {
            map = (Map<String, Object>) object;
        } else {
            try {
                map = BeanMapUtil.beanToMap(object);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        // 默认加密方式:不输入使用sha256,其它可选择项md5,sha1,sha3-256
        long ts = System.currentTimeMillis();
        String sign = "";
        String nonce = DigestUtils.md5Hex(System.currentTimeMillis() + "");
        String signSrc = "nonce" + nonce + "ts" + ts + "app_key" + junZiQianProperties.getAppKey() + "app_secret" + junZiQianProperties.getAppSecret();
        if (ENCRY_METHOD == null || "sha256".equalsIgnoreCase(ENCRY_METHOD)) {
            sign = DigestUtils.sha256Hex(signSrc);
        } else if ("sha1".equalsIgnoreCase(ENCRY_METHOD)) {
            sign = DigestUtils.sha1Hex(signSrc);
        } else if ("md5".equalsIgnoreCase(ENCRY_METHOD)) {
            sign = DigestUtils.md5Hex(signSrc);
        } else if ("sha3-256".equalsIgnoreCase(ENCRY_METHOD)) {
            // 此需要引入加密商BouncyCastleProvider才能使用
            sign = DigestUtils.sha3_256Hex(signSrc);
        }
        map.put("ts", ts);
        map.put("app_key", junZiQianProperties.getAppKey());
        map.put("sign", sign);
        //这只是为了生成一个随机值
        map.put("nonce", nonce);
        if (ENCRY_METHOD != null) {
            //为''也不会传,在requestUtils中有判断
            map.put("encry_method", ENCRY_METHOD);
        }
        log.info("君子签请求============》{}，url：{}", JSON.toJSONString(map), url);
        String post = HttpUtil.post(url, map);
        JunZiQianResult result = JSON.parseObject(post, JunZiQianResult.class);
        log.info("君子签响应============》{}", JSON.toJSONString(post));
        HrException.isTrue(Boolean.TRUE.equals(result.getSuccess()), result.getMsg());
        return result;
    }
}
